import axios from "axios";
import {isBlob} from "@/utils/validate.js";
import {getToken} from "@/utils/token.js";
import { ElLoading, ElMessage } from 'element-plus'
import request, {errorCode} from "@/utils/request.js";
import {tansParams} from "@/utils/index.js";
import FileSaver from 'file-saver';


const baseURL = import.meta.env.VITE_APP_BASE_API
let downloadLoadingInstance;

async function printErrMsg(data) {
    const resText = await data.text();
    const rspObj = JSON.parse(resText);
    const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
    ElMessage.error(errMsg);
}

export const useDownload = () => ({
    /**
     * 下载OSS文件
     * @param ossId 存储ID
     */
    async oss(ossId) {
        downloadLoadingInstance = ElLoading.service({ text: "正在下载数据，请稍候", background: "rgba(0, 0, 0, 0.7)" })
        const url = baseURL + '/system/oss/download/' + ossId
        try {
            const res = await axios({
                method: 'get',
                url: url,
                responseType: 'blob',
                headers: { 'Authorization': 'Bearer ' + getToken() }
            });

            const _isBlob = isBlob(res.data);
            if (_isBlob) {
                const blob = new Blob([res.data], { type: 'application/octet-stream' })
                FileSaver.saveAs(blob, decodeURIComponent(res.headers['download-filename']))
            } else {
                printErrMsg(res.data);
            }
            downloadLoadingInstance.close();
            
        }catch (e) {
            console.error(e)
            ElMessage.error('下载文件出现错误，请联系管理员！')
            downloadLoadingInstance.close();
        }
    },
    /**
     * 下载压缩包
     * @param url
     * @param name
     */
    async zip(url, name) {
        downloadLoadingInstance = ElLoading.service({ text: "正在下载数据，请稍候", background: "rgba(0, 0, 0, 0.7)" })
        url = baseURL + url
        try {
            const res = await axios({
                method: 'get',
                url: url,
                responseType: 'blob',
                headers: {
                    'Authorization': 'Bearer ' + getToken(),
                    'datasource': localStorage.getItem("dataName")
                }
            })
            const _isBlob = isBlob(res.data);
            if (_isBlob) {
                const blob = new Blob([res.data], { type: 'application/zip' })
                FileSaver.saveAs(blob, name)
            } else {
                printErrMsg(res.data);
            }
            downloadLoadingInstance.close();
        }catch (e) {
            console.error(e)
            ElMessage.error('下载文件出现错误，请联系管理员！')
            downloadLoadingInstance.close();
        }
    },
    /**
     * 从服务端接口下载文件
     * @param url 接口地址
     * @param params 参数
     * @param filename 文件名
     * @param config 其他请求配置
     * @returns {Promise<void>}
     */
    async downloadByApi(url, params, filename, config = {}) {
        downloadLoadingInstance = ElLoading.service({ text: "正在下载数据，请稍候", background: "rgba(0, 0, 0, 0.7)" })
        try {
            const data = await request.post(url, params, {
                transformRequest: [(params) => { return tansParams(params) }],
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                responseType: 'blob',
                ...config
            })
            const _isBlob = isBlob(data);
            if (_isBlob) {
                const blob = new Blob([data])
                FileSaver.saveAs(blob, filename)
            } else {
                printErrMsg(data)
            }
            downloadLoadingInstance.close();
        }catch (e) {
            console.error(e)
            ElMessage.error('下载文件出现错误，请联系管理员！')
            downloadLoadingInstance.close();
        }
    }

})
